<?php
/**
 * 支付API
 * @author wyb
 */
namespace app\common\extend;
use app\common\model\User as UserModel;
use app\store\model\Setting as SettingModel;
class Payapi extends Baseapi {
    
    /**
     * 发送支付
     * @param type $order_id
     * @param int $order_type 1商品订单   2会员卡订单
     */
    public function payment( $order_info , $pay_type = 1 , $order_type = 1) {
        if( !$order_info ) return false;
        $type = $pay_type == 1 ? 'Alipay' : 'WxPay';
        $obj_path = "app\\common\\extend\\pay\\".$type;
        $obj = new $obj_path;
		$body_info = '商品订单支付';
        $result = $obj->pay(['body' => $body_info , 'order_type' => $order_type , 'total_price' => $order_info['total_price'] , 'order_sn' => $order_info['order_no']]);
        if( $result['status'] === false ) {
            $this->_error = $result['msg'];
            return false;
        }
      //print_r( $result['data'] );
        return $result['data'];
    }
    
	/**
	 * 退款
	 */
	public function refund( $order_id , $price ) {
		if( !$order_id ) return false;
		$order_info = M('order')->where(['is_pay_status' => 2,'type' => 2,'id' => $order_id])->find();
		if( !$order_info ) {
			$this->_error = '退款订单不存在';
			return false;
		}
		if( $order_info['status'] != 5 ) {
			$this->_error = '订单已退款，重复请求';
			return false;
		}
		$type = $order_info['pay_type'] == 1 ? 'Alipay' : 'WxPay';
		$order_info['refund_fee'] = $price;
                $obj_path = "Common\\Api\\Pay\\".$type;
                $obj = new $obj_path;
		$result = $obj->orderRefund( $order_info , $price );
		if( $result['status'] === false ) {
			$this->_error = $result['msg'];
			return false;
		}
		M('order')->save(['id' => $order_id , 'status' => 7 , 'arrival_time' => time()]);
		return true;
	}
	
	/**
	 * 退款查询
	 */
	public function queryRefund() {
		$order_info = M('order')->where(['is_pay_status' => 2,'status' => 6])->select();
		if( $order_info ) {
			foreach( $order_info as $key => $value ) {
				$type = $order_info['pay_type'] == 1 ? 'Alipay' : 'WxPay';
				$obj_path = "Common\\Api\\Pay\\".$type;
				$obj = new $obj_path;
				$result = $obj->refundQuery( $value );
				if( $result === true ) {
					M('order')->save(['id' => $value['id'], 'status' => 7 , 'platform_time' => time() , 'arrival_time' => time() ] );
				}
			}
		}
	}
	
	/**
	 * 微信支付查询
	 */
	public function orderQuery( $order_id ) {
		$order_info = M('order')->where(['id' => $order_id])->field('order_sn,type')->find();
		$obj = new \Common\Api\Pay\WxPay();
		if( $obj->orderQuery( $order_info ) === true ) {
			return array('status' => 'success' , 'type' => $order_info['type']);
		}
		return array('status' => 'fail' , 'type' => $order_info['type']);
	}
	
    /**
     * 支付回调
     */
    public function notify( $type ) {
        $obj_path = "app\\common\\extend\\pay\\".$type;
        $obj = new $obj_path;
        $result = $obj->notify();
		if( $result !== false ) {
			//查询订单是否存在
			if( $result['type'] == 1 ) {
				$orderinfo = db("order")->where(['order_no' => $result['ordersn']])->find();
				if( !$orderinfo ) exit("订单不存在");
				if( $orderinfo['pay_status'] == 20 ) exit("订单已支付请勿重复支付");
				//写入日志
				db("user_money_log")->insert([
					'user_id' => $orderinfo['user_id'],
					'num' => $result['price'],
					'type' => 2,
					'content' => '通过'.($type == 'WxPay' ? '微信' : '支付宝').'支付【'.$result['ordersn'].'】订单金额【'.$result['price'].'】元',
					'create_time' => time()
				]);
				//修改订单状态
				db("order")->where(['order_no' => $result['ordersn']])->update(['pay_type' => $type == 'WxPay' ? 1 : 2 , 'pay_status' => 20 , 'pay_time' => time() , 'transaction_id' => $result['trade_no']]);
			} else {
				$orderinfo = db("member_cart_order")->where(['ordersn' => $result['ordersn']])->find();
				if( !$orderinfo ) exit("订单不存在");
				if( $orderinfo['status'] == 1 ) exit("订单已支付请勿重复支付");
				$user_info = db("user")->where(['user_id' => $orderinfo['user_id']])->find();
				if( !$user_info ) exit("用户数据不存在");
				//写入日志
				db("user_money_log")->insert([
					'user_id' => $orderinfo['user_id'],
					'num' => $result['price'],
					'type' => 2,
					'content' => '购买会员卡，通过'.($type == 'WxPay' ? '微信' : '支付宝').'共计支付【'.$result['price'].'】元',
					'create_time' => time()
				]);
				//修改订单状态
				db("member_cart_order")->where(['ordersn' => $result['ordersn']])->update(['pay_type' => $type == 'WxPay' ? 1 : 2 , 'status' => 1 , 'pay_time' => time() , 'transaction_id' => $result['trade_no'],'restart' => $user_info['is_open_cart']]);
				$setting = SettingModel::getItem('store');
				if( $setting['online_open_user'] == 1 ) {
					//判断是否有延迟开通
					$usermodel = new UserModel;
					if( $setting['yc_online_open_user'] == 1 ) {
						$usermodel->delay($orderinfo['id']);
					} else {
						//分销奖励
						$usermodel->builddistribution( $result['ordersn'] );
						//团队奖励
						//$usermodel->colonelReward($orderinfo['user_id'],$orderinfo['id']);
					}
				}
			}
		} else{
			exit("支付失败");
		}
    }
}